package com.example.micro.netty.server.nio.buffer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * scattering：将数据写入到Buffer时，可以采用Buffer数组，依次写入 [分散]
 * gathering：从Buffer读取数据时，可以采用Buffer数据，依次读 [聚集]
 */
public class ScatteringAndGatheringDemo {

    public static void main(String[] args) throws IOException {

        //使用 ServerSocketChannel 和 SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口到socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接（telnet）
        SocketChannel socketChannel = serverSocketChannel.accept();

        //假定从客户端接受8个字节
        int messageLength = 8;

        //循环读取
        while (true) {
            int byteRead = 0;

            while (byteRead < messageLength) {

                //*此处会阻塞住
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead=" + byteRead);

                //使用流打印，看看当前的这个Buffer的 position和limit
                Arrays.stream(byteBuffers)
                        .map(byteBuffer -> "position:" + byteBuffer.position() + " || limit:" + byteBuffer.limit())
                        .forEach(System.out::println);

                //使用流打印，看看当前的这个Buffer的 position和limit
                Arrays.stream(byteBuffers)
                        .map(x -> new String(x.array()))
                        .forEach(System.out::println);
            }

            //将所有的Buffer进行flip
            Arrays.stream(byteBuffers).forEach(Buffer::flip);

            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }

            Arrays.stream(byteBuffers).forEach(Buffer::clear);

            System.out.println("byteRead=" + byteRead + "||byteWrite=" + byteWrite + "||messageLength=" + messageLength);
        }

    }

}
